package cz.schovjan.mte_proj.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import cz.schovjan.mte_proj.Constant;
import cz.schovjan.mte_proj.R;
import cz.schovjan.mte_proj.activity.LyricActivity;
import cz.schovjan.mte_proj.dto.LyricResult;
import cz.schovjan.mte_proj.task.SearchLyricTask;

public class SearchByArtistSongFragment extends Fragment {

    /**
     * There must be default constructor, so passing data to instance we must solve some other way.
     */
    public SearchByArtistSongFragment() {
	super();
    }


    /**
     * Factory for creating fragments from data
     * @param type data passed to fragment
     * @return
     */
    public static SearchByArtistSongFragment createInstance() {
	SearchByArtistSongFragment df = new SearchByArtistSongFragment();
	return df;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View v = inflater.inflate(R.layout.fragment_search_by_artist_song, container, false);
	final Activity a = this.getActivity();
	final ListView lv = (ListView) v.findViewById(R.id.sasLvData);
	lv.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
		// vyhozeni okna s textem pisne
		Intent la = new Intent(v.getContext(), LyricActivity.class);
		la.putExtra(Constant.LYRIC, ((LyricResult) lv.getItemAtPosition(position)));
		startActivity(la);
	    }
	});
	Button b = (Button) v.findViewById(R.id.sasBtSearch);
	b.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		// spustit vyhledavani
		EditText etArtist = (EditText) getActivity().findViewById(R.id.etArtist);
		EditText etSong = (EditText) getActivity().findViewById(R.id.etSong);
		String artist = etArtist.getText().toString();
		String song = etSong.getText().toString();
		if (artist.isEmpty() || song.isEmpty()) {
		    Toast.makeText(a, R.string.err_empty_artist_song, Toast.LENGTH_SHORT).show();
		} else {
		    SearchLyricTask st = new SearchLyricTask(a, lv);
		    st.execute(artist, song);
		}
	    }
	});
	return v;
    }
}
